﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using Yqd.Controllers.Filter;
using Adp.Common;
using System.Linq;
using System;
using Yqd.Core;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Yqd.Enm;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxSpecialSuperviseController : Controller
    {
        YqdContext ctx;

        public WxSpecialSuperviseController(YqdContext ctx)
        {
            this.ctx = ctx;
        }

        [User]
        public ActionResult GetList()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var supervise = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
            if (supervise == null)
            {
                return this.ToJson(new
                {
                    success = true,
                    data = new List<object>()
                });
            }
            string TaskName = "", TypeName = "";
            JObject Targets = null;
            var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == supervise.TaskID);
            if (task != null) TaskName = task.Name;
            var type = ctx.Yqd_SpecialTaskType.FirstOrDefault(it => it.TypeID == supervise.TypeID);
            if (type != null) TypeName = type.Name;
            var field = ctx.Yqd_SpecialTemplate.Where(it => it.IsGeneral || (it.TaskID == supervise.TaskID && it.TypeID == supervise.TypeID));
            var target = ctx.Yqd_SpecialTarget.FirstOrDefault(it => it.TargetID == supervise.TargetID);
            if (target != null && target.Content.HasValue())
            {
                Targets = JObject.Parse(target.Content);
            }
            var assign = ctx.Yqd_Assign.Where(it => it.ItemID == SuperviseID && it.ItemType == 事项类型.专项督查).ToList();
            var l = WxUser.LogonInfo;
            var DeptRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.部门联络员);
            var MsRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.督查人员);
            var plan = ctx.Yqd_JobPlan.Where(it => it.CheckStatus != 审核状态.退回 && it.ItemType == 事项类型.专项督查).ToList();
            var bplan = ctx.Yqd_JobPlan.Where(it => it.CheckStatus == 审核状态.退回 && it.ItemType == 事项类型.专项督查).ToList();
            var progress = ctx.Yqd_PlanProgress.Where(it => it.CheckStatus != 审核状态.退回 && it.ItemType == 事项类型.专项督查).ToList();
            var bprogress = ctx.Yqd_PlanProgress.Where(it => it.CheckStatus == 审核状态.退回 && it.ItemType == 事项类型.专项督查).ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            return this.ToJson(new
            {
                success = true,
                DeptRole,
                MsRole,
                TaskName,
                TypeName,
                Fields = field.OrderBy(it => it.Tactic).ToList().Select(it => new
                {
                    it.FieldID,
                    it.Name
                }),
                Targets,
                supervise.Problem,
                Photos = !string.IsNullOrWhiteSpace(supervise.Photos) ? JArray.Parse(supervise.Photos) : new JArray(),
                CheckUnit = dept.FirstOrDefault(it => it.UnitCode == supervise.CheckUnit)?.Name,
                supervise.Checker,
                CheckInstime = supervise.CheckInstime.ToString("yyyy-MM-dd"),
                Status = supervise.Status.ToString(),
                AssignLimit = supervise.Instime.AddDays(7).ToString("yyyy-MM-dd"),
                ShowAssign = !assign.Any(s => s.ItemID == supervise.SuperviseID) || !plan.Any(m => m.ItemID == supervise.SuperviseID),
                Assign = assign.Select(n => new
                {
                    n.AssignID,
                    Item = n.Item ?? "",
                    n.LeadUnit,
                    ShowHistory = bplan.Any(b => b.AssignID == n.AssignID),
                    Dept = dept.FirstOrDefault(d => d.UnitCode == n.LeadUnit)?.Name,
                    AssignLimit = n.AssignLimit.ToString("yyyy.MM.dd"),
                    AssignTime = n.Instime.ToString("yyyy.MM.dd"),
                    AssignMan = user.FirstOrDefault(m => m.EmployeeCode == n.EmployeeCode)?.Name,
                    IsCheck = plan.Any(m => m.AssignID == n.AssignID && m.CheckStatus == Enm.审核状态.待审),
                    IsChecked = plan.Any(m => m.AssignID == n.AssignID && m.CheckStatus == Enm.审核状态.同意),
                    ShowAgree = progress.Any(b => b.AssignID == n.AssignID && b.CheckStatus == 审核状态.待审),
                    Plan = plan.Where(m => m.AssignID == n.AssignID).ToList().Select(s => new
                    {
                        s.PlanID,
                        Measure = s.Measure ?? "",
                        s.Leader,
                        s.Linkman,
                        ShowHistory = bprogress.Any(b => b.PlanID == s.PlanID),
                        IsChecked = s.CheckStatus == Enm.审核状态.同意,
                        Status = Enum.GetName(typeof(Enm.任务计划完成状态), s.Status),
                        PlanCompleteTime = s.PlanCompleteTime != null ? s.PlanCompleteTime.ToString("yyyy.MM.dd") : "",
                        Progress = progress.Where(b => b.PlanID == s.PlanID).OrderByDescending(c => c.Instime).ToList().Select(m => new
                        {
                            m.ProgressID,
                            IsCheck = m.CheckStatus == Enm.审核状态.待审,
                            IsDeal = m.PlanStatus == Enm.任务计划办理情况.申请延期,
                            PlanStatus = m.PlanStatus == 0 ? "" : m.PlanStatus.ToString(),
                            PlanResult = m.PlanResult ?? "",
                            DelayReason = m.DelayReason ?? "",
                            DelayTime = m.DelayTime != null ? m.DelayTime.ToString("yyyy.MM.dd") : ""
                        })
                    })
                })
            });
        }

        [User]
        public ActionResult GetSumList()
        {
            var TaskID = Form.GetInt("TaskID");
            var TypeID = Form.GetInt("TypeID");
            var sdate = Form.GetDateTime("sdate", DateTime.Now.Date);
            var edate = Form.GetDateTime("edate", DateTime.Now.Date);
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 0);
            var ed = edate.AddDays(1);
            var assigns = ctx.Yqd_Assign.Where(it => it.ItemType == 事项类型.专项督查 && it.Instime >= sdate && it.Instime < ed).Select(it => new { it.AssignID, it.ItemID, it.LeadUnit, it.AssignLimit, it.Instime }).ToList();
            var sIDs = assigns.Select(it => it.ItemID).ToArray();
            var supervises = ctx.Yqd_SpecialSupervise.Where(it => sIDs.Contains(it.SuperviseID)).Select(it => new { it.SuperviseID, it.TargetID, it.Problem }).ToList();
            var template = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.Name == "督查对象");
            var fieldid = "";
            if (template != null) fieldid = template.FieldID;
            var tIDs = supervises.Select(it => it.TargetID).ToArray();
            var targets = ctx.Yqd_SpecialTarget.Where(it => tIDs.Contains(it.TargetID)).Select(it => new { it.TargetID, it.Content }).ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var data = new List<object>();
            foreach (var s in supervises)
            {
                var t = targets.FirstOrDefault(it => it.TargetID == s.TargetID);
                if (t != null && t.Content.HasValue())
                {
                    var o = JObject.Parse(t.Content);
                    string Target = "", AssignLimit = "", LeadUnit = "";
                    if (fieldid != "")
                    {
                        Target = o[fieldid].ToString();
                    }
                    var a = assigns.FirstOrDefault(it => it.ItemID == s.SuperviseID);
                    if (a != null)
                    {
                        LeadUnit = dept.FirstOrDefault(it => it.UnitCode == a.LeadUnit)?.Name;
                        AssignLimit = a.AssignLimit.ToString("yyyy.MM.dd");
                    }
                    data.Add(new
                    {
                        s.SuperviseID,
                        s.Problem,
                        LeadUnit,
                        AssignLimit
                    });
                }
            }
            var totalcount = data.Count();
            if (pagesize > 0)
            {
                data = data.Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }
            return this.ToJson(new
            {
                success = true,
                totalcount = data.Count(),
                data
            });
        }

        [User]
        public ActionResult GetSuperviseList()
        {
            var TaskID = Form.GetInt("TaskID");
            var TypeID = Form.GetInt("TypeID");
            var Status = Form.GetInt("Status", 0);
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 0);
            var r = ctx.Yqd_SpecialSupervise.AsQueryable();
            if (TaskID > 0)
            {
                r = r.Where(it => it.TaskID == TaskID);
            }
            if (TypeID > 0)
            {
                r = r.Where(it => it.TypeID == TypeID);
            }
            if (Status == 60) //60未完结
            {
                r = r.Where(it => it.Status == 办理情况.未回复 || it.Status == 办理情况.已回复 || it.Status == 办理情况.已滞后);
            }
            if (Status == 70) //70已交办
            {
                r = r.Where(it => it.Status > 办理情况.待交办);
            }
            if (Status == 80) //待办任务
            {
                r = r.Where(it => it.IsDeal);
            }
            switch ((办理情况)Status)
            {
                case 办理情况.待交办:
                    r = r.Where(it => it.Status == 办理情况.待交办);
                    break;
                case 办理情况.未回复:
                    r = r.Where(it => it.Status == 办理情况.未回复);
                    break;
                case 办理情况.已回复:
                    r = r.Where(it => it.Status == 办理情况.已回复 || it.Status == 办理情况.已完结);
                    break;
                case 办理情况.已完结:
                    r = r.Where(it => it.Status == 办理情况.已完结);
                    break;
                case 办理情况.已滞后:
                    r = r.Where(it => it.Status == 办理情况.已滞后);
                    break;
            }
            var assigns = ctx.Yqd_Assign.Where(it => it.ItemType == 事项类型.专项督查).Select(it => new { it.AssignID, it.ItemID, it.LeadUnit, it.AssignLimit, it.Instime }).ToList();
            var template = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.Name == "督查对象");
            var fieldid = "";
            if (template != null) fieldid = template.FieldID;
            var tIDs = r.Select(it => it.TargetID).ToArray();
            var targets = ctx.Yqd_SpecialTarget.Where(it => tIDs.Contains(it.TargetID)).Select(it => new { it.TargetID, it.Content }).ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var data = new List<object>();
            foreach (var s in r)
            {
                var t = targets.FirstOrDefault(it => it.TargetID == s.TargetID);
                if (t != null && t.Content.HasValue())
                {
                    var o = JObject.Parse(t.Content);
                    string Target = "", AssignLimit = "", LeadUnit = "";
                    if (fieldid != "")
                    {
                        Target = o[fieldid].ToString();
                    }
                    var a = assigns.FirstOrDefault(it => it.ItemID == s.SuperviseID);
                    if (a != null)
                    {
                        LeadUnit = dept.FirstOrDefault(it => it.UnitCode == a.LeadUnit)?.Name;
                        AssignLimit = a.AssignLimit.ToString("yyyy.MM.dd");
                    }
                    data.Add(new
                    {
                        s.SuperviseID,
                        s.Problem,
                        LeadUnit,
                        AssignLimit,
                        CheckUnit = dept.FirstOrDefault(it => it.UnitCode == s.CheckUnit)?.Name,
                        s.Checker,
                        CheckInstime = s.CheckInstime.ToString("yyyy.MM.dd")
                    });
                }
            }
            var totalcount = data.Count();
            if (pagesize > 0)
            {
                data = data.Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data
            });
        }

        /// <summary>
        /// 添加专项督查
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_SpecialSupervise model)
        {
            model.Instime = DateTime.Now;
            model.Status = 办理情况.待交办;
            model.IsDeal = false;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                TaskLogService.AddLog(model.TaskID, "提交专项督查");
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var ret = ctx.Database.ExecuteSql("delete from Yqd_SpecialSupervise where SuperviseID={0};", SuperviseID);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}